from django.contrib import admin
from .models import Scene, SceneExecution, SceneSchedule


@admin.register(Scene)
class SceneAdmin(admin.ModelAdmin):
    """场景管理"""
    list_display = ['name', 'trigger_type', 'is_active', 'created_by', 'created_at']
    list_filter = ['trigger_type', 'is_active', 'created_at']
    search_fields = ['name', 'description']
    ordering = ['-created_at']
    
    fieldsets = (
        ('基本信息', {
            'fields': ('name', 'description', 'icon', 'is_active')
        }),
        ('触发配置', {
            'fields': ('trigger_type', 'trigger_conditions')
        }),
        ('执行动作', {
            'fields': ('actions',)
        }),
        ('创建信息', {
            'fields': ('created_by', 'created_at', 'updated_at'),
            'classes': ('collapse',)
        }),
    )
    readonly_fields = ['created_at', 'updated_at']
    
    def save_model(self, request, obj, form, change):
        """保存时自动设置创建者"""
        if not change:  # 新建时
            obj.created_by = request.user
        super().save_model(request, obj, form, change)


@admin.register(SceneExecution)
class SceneExecutionAdmin(admin.ModelAdmin):
    """场景执行记录管理"""
    list_display = ['scene', 'status', 'trigger_source', 'started_at', 'completed_at']
    list_filter = ['status', 'trigger_source', 'started_at']
    search_fields = ['scene__name']
    ordering = ['-started_at']
    
    fieldsets = (
        ('执行信息', {
            'fields': ('scene', 'status', 'trigger_source', 'trigger_data')
        }),
        ('执行结果', {
            'fields': ('execution_result', 'error_message'),
            'classes': ('collapse',)
        }),
        ('时间信息', {
            'fields': ('started_at', 'completed_at'),
            'classes': ('collapse',)
        }),
    )
    readonly_fields = ['started_at', 'completed_at']
    
    def has_add_permission(self, request):
        """禁止手动添加执行记录"""
        return False


@admin.register(SceneSchedule)
class SceneScheduleAdmin(admin.ModelAdmin):
    """场景调度管理"""
    list_display = ['scene', 'schedule_type', 'is_active', 'next_run_time', 'created_at']
    list_filter = ['schedule_type', 'is_active', 'created_at']
    search_fields = ['scene__name']
    ordering = ['-created_at']
    
    fieldsets = (
        ('基本信息', {
            'fields': ('scene', 'schedule_type', 'is_active')
        }),
        ('调度配置', {
            'fields': ('schedule_time', 'recurrence_rule', 'cron_expression')
        }),
        ('执行状态', {
            'fields': ('next_run_time', 'last_run_time', 'run_count'),
            'classes': ('collapse',)
        }),
        ('时间信息', {
            'fields': ('created_at', 'updated_at'),
            'classes': ('collapse',)
        }),
    )
    readonly_fields = ['created_at', 'updated_at', 'next_run_time', 'last_run_time', 'run_count']
